import React from 'react'
import BaseScreen from '../BaseScreen'
import ProgressView from "../../view/ProgressView";
import PressTouch from '../../view/PressTouch'
import { MyButton } from '../../view/MyButton'
import { Actions, NameSpace } from "../../model/taskModel";
import { connect } from "react-redux";
import { back } from "../../utils/LocationUtil";
import styles from "../../css/AddCuiji.module.css";
import Config from "../../Config";
import Upload from '../components/Upload';
import { methodsList, targetsList, resultList, addrList, phoneList, cuiList } from '../../const/datas'
import SelectorInline from '../components/SelecorInline'
import SelectorBottom from '../components/SelectorBottom'
import UploadImgs from '../components/UploadImgs'
import { AddCuiji, Common,LOGIN_IMG } from '../../const/imgs'
import GetLocation from '../components/GetLocation'
import { HintDialog } from '../../view/Dialog'
import Textarea from '../components/TextArea'
import { collectRecordStore } from '../../service/TaskService'
import { getTOKEN, getIDs, getInfo } from '../../utils/StorageUtil'
import{filterImgs} from '../../utils/CommomUtil'
class AddCuiJI extends BaseScreen {
  constructor(props) {
    super(props);
    this.index = 0
    this.state = {
      method: {
        index: 0,
        name: methodsList[0].value
      },
      target: {
        index: 0,
        name: targetsList[0].value
      },
      result: {
        index: 0,
        name: resultList[0].value
      },
      remark: '',
      cui: { value: null },
      addr: { value: null },
      repayList: [{index:0}],
      locationInfo: {},
      loading: false
    }
  }
  componentDidMount() {
    document.title = '填写催记'
  }
  // 导航
  navigate = (e) => {
    this.setState({
      selectedIndex: e
    })
  }
  // 催款方式&对象&结果
  getMethod = (e) => {
    if (e.method && e.method.index != this.state.method.index) {
      // 切换催收方式，已选催收情况清空
      this.setState({
        cui: { value: null }
      })
    }
    this.setState(e)
  }
  // 催款情况&地址&
  getSelected = (e) => {
    this.setState(e)
  }
  //日期
  getDate = (e) => {
    const repayList = this.state.repayList
    for (let i in e) {
      repayList[i].date = e[i].value
    }
    this.setState({
      repayList: repayList
    })
  }
  // 还款金额
  getMoney = (e, index) => {
    const repayList = this.state.repayList
    repayList[index].money = e

    this.setState({
      repayList: repayList
    })
  }
  // 新增回款
  setMoreRepay = () => {
    this.index++;    
    const a = this.state.repayList
    const i = this.index
    a.push({index:i})
    this.setState({
      repayList: a
    })
  }
  deleteRepay =(index) => {
    const a = this.state.repayList
    a.splice(index,1)
    this.setState({
      repayList:a
    })
  }
  // 补充
  getRemark = (e) => {
    this.setState({
      remark: e
    })
  }
  // 定位
  getLocation = (e) => {
    this.setState({
      locationInfo: e
    })
  }
  confirm = () => {
    
    const { imgs } = this.refs
    const { imgList } = imgs.state
    const { remark, addr, cui, phone, method, result, target, repayList, locationInfo } = this.state
    const params = {
      token: getTOKEN(),
      task_id: this.props.taskId?this.props.taskId:getIDs().taskId,
      type: method.name,
      object: target.name,
      collect_result: cui.value,
      result: result.name,
      content: remark,
      pic: filterImgs(imgList),
      return_money: repayList.map((item)=>[item.money,item.date]),
      address: addr.value,
      coordinate: [locationInfo.lat, locationInfo.lng],
      daily_address: locationInfo.formattedAddress
    }

    if (method.name === '上门' && target.name === '本人' && addr.value === null) {
      this.showMsgDialog("请选择地址");
    } else if (method.name === '上门' && cui.value === null) {
      this.showMsgDialog("请选择催收情况");
    } else if (method.name === '电话' && cui.value === null) {
      this.showMsgDialog("请选择接听情况");
    } else if (result.name === '还款' && !this.checkRepay(repayList)) {
      return
    // } else if (remark === null || remark === '') {
    //   this.showMsgDialog("请填写补充说明");
    // } else if (!locationInfo.formattedAddress) {
    //   this.showMsgDialog("请定位当前地址");
    } else {
      this.summit(params)
    }
  }
  
  checkRepay = (repayList) => {
    let repay = 1
    for (let i = 0; i < repayList.length; i++) {
      let b = repayList[i].date && repayList[i].date !== '' ? 1 : 0
      if (b === 0) {
        this.showMsgDialog("请选择还款日期");
      }
      let c = repayList[i].money && parseInt(repayList[i].money) !== 0 ? 1 : 0     
      if (c === 0) {
        this.showMsgDialog("还款金额不能为 0 ");
      }    
      
      let a = repayList[i].money && repayList[i].money !== '' ? 1 : 0
      if (a === 0) {
        this.showMsgDialog("请填写还款金额");
      }
      repay *= a * b * c
    }
    return repay
  }
  summit = (params) => {
    this.setState({ loading: true });
    collectRecordStore(params)
      .then(
        res => {
          this.setState({ loading: false });
          if (res.error_code === 0) {
            this.refs.summit.setState({
              content: '提交成功',
              visibility: true
            });

          }

        }
      ).catch(
        err => {
          console.log(err)
        }
      )
  }
  render() {
    
    const { case_info } = this.props.TaskData?this.props.TaskData:getInfo('TaskInfo')
    const { method, repayList, result, target } = this.state
    const RepayList = repayList.map((item, index) => {
      return (
        <SelectorRepay key={item.index} index={index} getSelectedDate={this.getDate} getMoney={this.getMoney} item={item} deleteRepay={this.deleteRepay} />
      )
    })
    return (
      <div className={styles['home']} style={{ paddingTop: '10px' }}>
        <div className={styles['cuiji_item']}>
          <div className={styles['anjian_code']}>
            <span style={{ color: Config.fontColor1 }}>
              案件编号：
            </span>
            {case_info && case_info.commision_case_no}
          </div>
        </div>
        <SelectorInline list={methodsList} type='method' name='方式' getOption={this.getMethod} />
        <SelectorInline list={targetsList} type='target' name='对象' getOption={this.getMethod} />

        {
          // 上门催款
          method.index === 0 && target.index === 0 &&
          <div className={styles['cuiji_item']}>
            <SelectorBottom list={addrList} type='addr' name='地址' des="请选择" getSelected={this.getSelected} />
          </div>
        }{
          // 上门催款
          method.index === 0 &&
          <div className={styles['cuiji_item']}>
            <SelectorBottom list={cuiList} type='cui' name='催收情况' des="请选择" getSelected={this.getSelected} />
          </div>

        }{
          // 电话催款
          method.index === 1 &&
          <div className={styles['cuiji_item']}>
            <SelectorBottom list={phoneList} type='cui' name='接通情况' des="请选择" getSelected={this.getSelected} />
          </div>
        }

        <SelectorInline list={resultList} type='result' name='结果' getOption={this.getMethod} />

        {result.index === 0 &&
          <div>

            {/* 还款金额 */}
            {RepayList}

            <div className={styles['btn_wrapper']}>
              <MyButton
                style={{
                  width: '40%',
                }}
                name={"新增回款"}
                onClick={
                  this.setMoreRepay
                }
              />
            </div>
          </div>
        }

        {/* 补充 */}
        <div className={styles['cuiji_item']}>
          <div className={styles['cuiji_item3']}>
            <div className={styles['cuiji_item_key']}>
              补充
            </div>
          </div>
          <div className={styles['cuiji_item3']}>
            <Textarea
              style={inputStyle}
              onChange={this.getRemark}
            />
            {/* 图片上传 */}
            <UploadImgs ref='imgs' />
          </div>
        </div>

        <GetLocation
          getLocation={this.getLocation}
          formattedAddress={this.state.locationInfo.formattedAddress}
          visibility={true}
          immediately={true}
        />
        <div className={styles['btn_wrapper']} style={{ padding: '40px 0' }}>
          <MyButton
            style={{
              width: '80%',
              borderRadius: '0.3rem'
            }}
            name={"确认提交"}
            onClick={() => {
              this.confirm();
            }}
          />
        </div>
        <HintDialog
          ref="dialog"
          style={{
            color: "#fff"
          }}
          visibility={this.state.alertMsg !== ""}
          content={this.state.alertMsg}
          operateText="确定"
        />
        <HintDialog
          ref="summit"
          style={{
            color: "#fff"
          }}
          visibility={this.state.alertMsg !== ""}
          content={this.state.alertMsg}
          operateText="确定"
          operateClick={() => { back() }}
        />
      <ProgressView visibility={this.state.loading} mode={ProgressView.MODE_MEDIUM} />        
        
      </div>
    )
  }
}
class SelectorRepay extends React.Component {
  constructor(props) {
    super(props);
  }
  getMoney = (e) => {
    this.props.getMoney(e.target.value, this.props.index)
  }
  render() {
    const { index, getSelectedDate, getMoney, item, deleteRepay } = this.props
    return (
      <div className={styles['cuiji_item']}>
        <div className={styles['cuiji_item3']}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>
              还款金额
                <span style={{ color: Config.fontColor1 }}>
                (共需还款
                  <span style={{ color: '#ff9d03' }}>26505.33</span>
                元)
                </span>
            </span>
              {index>0&&<img src={LOGIN_IMG.DEL.source.url} alt='' style={{width:'16px',height:'16px'}} onClick={()=>{deleteRepay(index)}} />}
          </div>
          <div>
            ￥ <input style={inputStyle} onChange={this.getMoney} />
          </div>
        </div>
        <SelectorBottom list={resultList} getSelected={getSelectedDate} type={index} name='还款时间' des="选择时间" />
      </div>
    )
  }
}


const mapStateToProps = state => {
  return {
    ...state[NameSpace]
  };
};

// const mapDispatchToProps = dispatch => {
//   return {
//     selectItem(taskId) {
//       let params = {
//         taskId: taskId,
//       };
//       dispatch(Actions.actionSelectId(params));
//     }
//   };
// };

const inputStyle = { border: 'none', outline: 'none' }
export default connect(mapStateToProps)(AddCuiJI);
// export default AddCuiji;